package com.fyt.config.interceptor;

import com.fyt.entity.User;
import com.fyt.mapper.UserMapper;
import com.fyt.service.Impl.utils.UserDetailsImpl;
import com.fyt.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private UserMapper userMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        //获取前端请求头中的的Authorization的值
        String token = request.getHeader("Authorization");
        System.out.println(token);
        System.out.println(request.getRequestURI());

        //判断token是否是"Bearer "开头和token是否为空
        if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            LocalDateTime.now();
            return;
        }
        //token如果合法则除去开头的"Bearer "，留下真正的token
        token = token.substring(7);

        String userid;
        try {
            //通过jwt工具类解析token获取token中的userid
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //通过token中解析出的id从数据库查询user是否存在
        User user = userMapper.selectById(Integer.parseInt(userid));

        if (user == null) {
            throw new RuntimeException("用户名未登录");
        }

        //UserDetailsImpl是Security自带的封装用户信息等类，
        UserDetailsImpl loginUser = new UserDetailsImpl(user);

        //通过UsernamePasswordAuthenticationToken类表示从封装的用户类信息的实例中获取用户信息，
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);

          //把用户信息存储到Security上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //开始下一个请求
        filterChain.doFilter(request, response);
    }
}
